<?php

class Posts extends BaseModel {
    
    public $table = "blog_posts";
    
    /**
     * 发布一篇内容
     * @param array $data 中间必须要包含一个type的参数
     * @return integer last_insert_id();
     */
    public function publish($data = array()) {
        if(!is_array($data)) {
            $data = array("type" => $data);
        }
        $method = "publish_".$data['type'];
        global $user;
        $datas = array(
            "uid" => $user->uid,
            "blogid" => abs(intval($_POST["post_to"])),
            "subject" => h($_POST['subject']),
            "content" => remove_xss($_POST["text"]),
            "dateline"=> CURRENT_TIMESTAMP,
            "private" => abs(intval($_POST["private"])),
            "toped"   => abs(intval($_POST["toped"])),
            "favorites" => 0,
            "replies" => 0,
            "is_submit" => $data["is_submit"] ? 1 : 0
        );
        
        $datas = array_merge($datas, $data);
        
        /**
         * @todo 验证是否为本人博客
         * @todo 投稿
         * @todo 自定义链接
         */
        
        if(method_exists($this, $method)) {
            return $this->$method($datas);
        } else {
            return false;
        }
    }
    
    /**
     * 取得个人首页要显示的文章
     * @param integer $uid
     * @todo get following
     */
    public function get_index_posts($uids, $offset=20) {
        $uids = is_array($uids) ? $uids : array($uids);
        $following = array();
        
        $uids = array_merge($uids, $following);
        
        if(!$uids) {
            return array();
        }
        
        $condition = sprintf(" WHERE bp.uid IN(0,%s)", implode(",", $uids));
        $total = $this->count(str_replace("bp.uid", "uid", $condition));
        $blog_table = $this->get_table("blogs");
        
        $sql = "SELECT bp.*, b.avatar, b.name as blog_name, b.sub_domain
                FROM {$this->table} bp
                LEFT JOIN {$blog_table} b ON b.id = bp.blogid
                {$condition}
                ORDER BY bp.id DESC";
        
        /**
         * @todo 获得文章tag
         * @todo 获取当前用户是否喜欢此文章
         */
                
        require PROJECT_DIR."/lib/class.paginator.php";
        $p = new Paginator($this->db, $_GET["page"], $offset);
        return $p->work($sql, $total);
    }
    
    /**
     * 发布文字
     */
    private function publish_text($datas) {
        return $this->insert($datas);
    }
}